<!-- 组件说明 -->
<template>
  <div class='roles'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb> 
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <!-- 添加角色按钮 -->
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表表格 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['border_bottom',i1 == 0?'border_top':'','vertical_center']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag type="primary" closable @close="deleteRight(item1.id,scope.row)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 == 0?'':'border_top','vertical_center']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <!-- 二级标签 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRight(item2.id,scope.row)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级标签 -->
                  <el-col :span="18">
                    <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="deleteRight(item3.id,scope.row)" type="warning">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="showEditRoleDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteRole(scope.row.id)" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" @click="showSetRightDialog(scope.row)" icon="el-icon-s-tools">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
        <!-- 内容区域 -->
        <el-tree :data="rightsList" ref="righttree" show-checkbox node-key="id" default-expand-all :default-checked-keys="defaultCheckedKeys" :props="rightDefaultProps">
        </el-tree>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClose">
        <!-- 内容区域 -->
        <el-form :model="addRoleList" :rules="addRoleRules" ref="addRoleRuleForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑啊角色对话框 -->
      <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleDialogClose">
        <!-- 内容区域 -->
        <el-form :model="editRoleList" :rules="addRoleRules" ref="editRoleRuleForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  //import x from ''
  export default {
    components: {

    },
    data () {

      return {
        //存储角色列表数据
        rolesList: [],
        //分配权限对话框
        setRightDialogVisible: false,
        // 获取权限列表
        rightsList: [],
        // 显示树形权限列表的默认属性
        rightDefaultProps: {
          children: 'children',
          label: 'authName'
        },
        //默认选中的项
        defaultCheckedKeys: [],
        roleId: 0,
        //添加角色对话框显示/隐藏
        addRoleDialogVisible: false,
        //添加角色表单内容
        addRoleList:{
          roleName: '',
          roleDesc: ''
        },
        //编辑啊角色对话框显示/隐藏
        editRoleDialogVisible:false,
        // 编辑角色框内容绑定
        editRoleList:{
          roleName: '',
          roleDesc: '',
          id: ''
        },
        //添加角色表单规则
        addRoleRules:{
          roleName:[
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          roleDesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' }
          ]
        }
      };
    },
    created(){
      this.getRolesList()
    },
    methods: {
      //获取角色列表
      async getRolesList(){
        const{data:res} = await this.$http.get('roles')
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rolesList = res.data
        console.log(this.rolesList);
      },
      // 删除三级权限
      async deleteRight(right_id,role){
        //弹框提示用户是否要删除
        let str = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(str !== 'confirm') return this.$message.info('已取消删除操作')
        const{data:res} = await this.$http.delete(`roles/${role.id}/rights/${right_id}`)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('删除权限成功！')
        // this.getRolesList()
        role.children = res.data
      },
      // 显示分配权限对话框
      async showSetRightDialog(role){
        this.setRightDialogVisible = true
        //保存roleId
        this.roleId = role.id
        // 获取所有权限列表
        const{data:res} = await this.$http.get('rights/tree')
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rightsList = res.data
        //渲染被选中的权限框
        this.getLeafKeys(role,this.defaultCheckedKeys)
      },
      //通过递归的形式，获取角色下所有三级权限的id，并保存到defaultCheckedKeys数组中
      getLeafKeys(node,arr){
        if(!node.children){
          //如果当前node节点不包含children属性，则其是三级节点 
          return arr.push(node.id)
        }
        node.children.forEach((item)=>{
          this.getLeafKeys(item,arr)
        })
      },
      // 监听关闭分配权限对话框的关闭事件
      setRightDialogClose(){
        this.defaultCheckedKeys = []
      },
      // 确定修改权限分配
      async allotRights(roleId){
        // 获取选中叶子节点的id
        let checked = this.$refs.righttree.getHalfCheckedKeys()
        //获取半选中叶子节点的id
        let halfChecked = this.$refs.righttree.getCheckedKeys()
        const keys = [...checked,...halfChecked].join(',')
        const{data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: keys})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success("修改权限成功")
        this.getRolesList()
        this.setRightDialogVisible = false
      },
      //删除角色事件
      async deleteRole(roleId){
        const str = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(str !== 'confirm') return this.$message.info("已取消删除")
        const{data:res} = await this.$http.delete(`roles/${roleId}`)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('删除成功')
        this.getRolesList()
      },
      //添加角色对话框关闭时 清除内容
      addRoleDialogClose(){
        this.$refs.addRoleRuleForm.resetFields()
      },
      //添加角色事件
      addRole(){
        this.$refs.addRoleRuleForm.validate(async (valid) => {
          if (!valid) {
            return this.$message.error("添加角色出错")
          } else {
            const{data:res} = await this.$http.post('roles',this.addRoleList)
            if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
            this.$message.success('添加角色成功')
            this.getRolesList()
            this.addRoleDialogVisible = false
          }
        })
      },
      //显示/隐藏编辑对话框
      showEditRoleDialog(roleInfo){
        this.editRoleDialogVisible = true
        console.log('roleInfo',roleInfo);
        this.editRoleList.roleName = roleInfo.roleName
        this.editRoleList.id = roleInfo.id
        this.editRoleList.roleDesc = roleInfo.roleDesc
      },
      //关闭编辑对话框 清空内容
      editRoleDialogClose(){
        this.$refs.editRoleRuleForm.resetFields()
      },
      //编辑角色信息
      editRole(){
        this.$refs.editRoleRuleForm.validate(async (valid) => {
          if (!valid) {
            return this.$message.error("添加角色出错")
          } else {
            const{data:res} = await this.$http.put(`roles/${this.editRoleList.id}`,{roleName:this.editRoleList.roleName,roleDesc:this.editRoleList.roleDesc})
            if(res.meta.status !== 200){
              return this.$message.error(res.meta.msg)
            } else{
              this.$message.success('编辑角色成功')
              this.getRolesList()
              this.editRoleDialogVisible = false
            }
            
          }
        })
        
      }
    }
  }
  
</script>

<style lang='less' scoped>
//@import url()
.el-tag{
  margin: 7px;
}
.border_top{
  border-top: 1px solid #eee;
}
.border_bottom{
  border-bottom: 1px solid #eee;
}
.vertical_center{
  display: flex;
  align-items: center;
}
</style>